<?php

namespace App\Providers;

use App\Listeners\DBSqlListener;
use Illuminate\Auth\Events\Registered;
use Illuminate\Auth\Listeners\SendEmailVerificationNotification;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array<class-string, array<int, class-string>>
     */
    protected $listen = [
        Registered::class => [
            SendEmailVerificationNotification::class,
        ],
        //绑定监听的sql事件
        QueryExecuted::class => [
            DBSqlListener::class,
            // ...其他监听事件
        ],
    ];

    /**
     * Register any events for your application.
     *
     * @return void
     */
    public function boot()
    {
        parent::boot();
        // 或者把监听事件写在这里
        // 监听数据库事件,进行断点打印,并记录到sql日志中
        /*DB::listen(function (QueryExecuted $event){
            $sql = $event->sql;//执行的sql
            $bindings = $event->bindings;//执行的参数
            $time = $event->time;//执行的时间

            // 如果是字符串 带上引号
            $bindings = array_map(function ($binding) {
                if(is_string($binding)){
                    return "'$binding'";
                } else if($binding instanceof \DateTime) { // 如果是时间
                    return $binding->format("'Y-m-d H:i:s'");
                }
                return $binding;
            },$bindings);
            //拼装sql
            $sql = str_replace('?','%s',$sql);
            // 填充参数
            //$sql = vsprintf($sql,$bindings);
            $sql = sprintf($sql,...$bindings);
            // 记录到日志
            Log::info('sql log',['sql'=>$sql,'time' =>$time.'ms']);
        });*/
    }
}
